<template>
  <div class="my-favorites">
    <el-card class="favorites-card">
      <template #header>
        <div class="card-header">
          <h3>我的收藏</h3>
          <div class="header-info">
            <el-text type="info">共收藏了 {{ total }} 辆车</el-text>
          </div>
        </div>
      </template>

      <div v-loading="loading" class="favorites-content">
        <div v-if="favorites.length === 0" class="empty-state">
          <el-empty description="还没有收藏任何车辆">
            <el-button type="primary" @click="$router.push('/user/carBrowse')">去看看车辆</el-button>
          </el-empty>
        </div>

        <div v-else class="favorites-list">
          <el-row :gutter="20">
            <el-col :span="8" v-for="favorite in favorites" :key="favorite.id">
              <el-card class="favorite-item" shadow="hover">
                <div class="car-image">
<!--                  <img :src="favorite.carImages || '/default-car.jpg'" :alt="favorite.carBrand + ' ' + favorite.carModel" />-->
                  <img :src="`/api/file/download.do?filename=${favorite.carImages}`"
                       :alt="favorite.carBrand + ' ' + favorite.carModel" />
                  <div class="car-status">
                    <el-tag :type="favorite.carStatus === 0 ? 'success' : 'danger'" size="small">
                      {{ favorite.carStatus === 0 ? '可租用' : '已租出' }}
                    </el-tag>
                  </div>
                </div>

                <div class="car-info">
                  <h4 class="car-title">{{ favorite.carBrand }} {{ favorite.carModel }}</h4>
                  <p class="car-plate">车牌号：{{ favorite.licensePlate }}</p>
                  <div class="car-price">
                    <span class="price">¥{{ favorite.dailyRent }}</span>
                    <span class="unit">/天</span>
                  </div>
                  <div class="favorite-time">
                    <el-text type="info" size="small">
                      收藏于：{{ formatDate(favorite.createdTime) }}
                    </el-text>
                  </div>
                </div>

                <div class="car-actions">
                  <el-button 
                    type="primary" 
                    size="small" 
                    :disabled="favorite.carStatus !== 0"
                    @click="goToDetail(favorite.carId)"
                  >
                    查看详情
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="removeFavorite(favorite)"
                    :loading="removing === favorite.id"
                  >
                    取消收藏
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[6, 12, 18, 24]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserFavorites, removeFromFavorites } from '@/api/car'
import { useUserInfoStore } from '@/stores/userInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 数据
const loading = ref(false)
const favorites = ref([])
const currentPage = ref(1)
const pageSize = ref(6)
const total = ref(0)
const removing = ref(null)

// 方法
const loadFavorites = async () => {
  loading.value = true

  try {
    const response = await getUserFavorites({
      userId: userInfoStore.userInfo?.id || '', // 从用户状态获取当前登录用户ID
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })

    favorites.value = response.data.records || []
    total.value = response.data.count || 0
    
  } catch (error) {
    ElMessage.error('加载收藏列表失败')
    console.error('加载收藏列表失败:', error)
  } finally {
    loading.value = false
  }
}

const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.getFullYear() + '-' + 
         String(d.getMonth() + 1).padStart(2, '0') + '-' + 
         String(d.getDate()).padStart(2, '0')
}

const goToDetail = (carId) => {
  router.push(`/user/carDetail/${carId}`)
}

const removeFavorite = async (favorite) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消收藏 ${favorite.carBrand} ${favorite.carModel} 吗？`,
      '取消收藏',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    removing.value = favorite.id

    await removeFromFavorites({
      userId: userInfoStore.userInfo?.id || '', // 从用户状态获取当前登录用户ID
      carId: favorite.carId
    })

    ElMessage.success('取消收藏成功')
    loadFavorites() // 重新加载列表
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消收藏失败')
      console.error('取消收藏失败:', error)
    }
  } finally {
    removing.value = null
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadFavorites()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadFavorites()
}

// 初始化
onMounted(() => {
  loadFavorites()
})
</script>

<style scoped>
.my-favorites {
  padding: 20px;
}

.favorites-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.favorites-content {
  min-height: 400px;
}

.empty-state {
  text-align: center;
  padding: 50px 0;
}

.favorites-list {
  margin-bottom: 20px;
}

.favorite-item {
  margin-bottom: 20px;
  height: 100%;
}

.car-image {
  position: relative;
  width: 100%;
  height: 150px;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 15px;
}

.car-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.car-status {
  position: absolute;
  top: 10px;
  right: 10px;
}

.car-info {
  margin-bottom: 15px;
}

.car-title {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
  font-weight: bold;
}

.car-plate {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.car-price {
  margin: 8px 0;
}

.car-price .price {
  font-size: 18px;
  font-weight: bold;
  color: #e6a23c;
}

.car-price .unit {
  font-size: 14px;
  color: #909399;
  margin-left: 3px;
}

.favorite-time {
  margin-top: 8px;
}

.car-actions {
  display: flex;
  gap: 8px;
}

.car-actions .el-button {
  flex: 1;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
